﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IntelligentDecisioning.SharePoint.Helpers;
using Microsoft.SharePoint;

namespace IntelligentDecisioning.SharePoint.Logging
{
    public class FeatureInstallationLog: ILog
    {
        private Guid _featureId;
        private String _featureDisplayName;
        private SPSite _site;

        public FeatureInstallationLog(String featureDisplayName, Guid featureId, SPSite site)
        {
            _featureDisplayName = featureDisplayName;
            _featureId = featureId;
            _site = site;
        }

        public void WriteToLog(String message)
        {
            WriteToLog(message, "Information");
        }

        private void WriteToLog(String message, String category)
        {
            IDListHelper listHelper = new IDListHelper(_site, _site.RootWeb);
            if (listHelper.ListExists(SharePointConfiguration.FEATURE_INSTALLATION_LOG))
            {
                try
                {
                    SPList intallationLogList = listHelper.GetList(SharePointConfiguration.FEATURE_INSTALLATION_LOG);
                    SPListItem logEntry = intallationLogList.Items.Add();
                    logEntry["Title"] = _featureDisplayName;
                    logEntry["FeatureId"] = _featureId;
                    logEntry["Category"] = category;
                    logEntry["Message"] = message;
                    logEntry.Update();
                    intallationLogList.Update();
                }
                catch { }
            }
        }

        public void WriteToLog(String message, Exception e)
        {
            String errMsg = "Exception details are - " + e.Message;
            while (e.InnerException != null)
            {
                errMsg += " Inner exception message: " + e.InnerException.Message;
                e = e.InnerException;
            }

            WriteToLog(message + errMsg, "Error");
        }
       
    }
}
